package lc.链表;

import utils.ListNode;

/**
 * @description: 链表中倒数第k个节点
 * @author: qian
 * @createDate: 2021/9/2
 */
public class JzOffer22 {
    /**
     * 定义两个指针一个指针先走k步
     * @param head
     * @param k 倒数第k个数
     * @return
     */

    public ListNode getKthFromEnd(ListNode head, int k) {

        ListNode n1 = head;
        ListNode n2 = head;
        while(n2 != null && k > 0) {

            n2 = n2.next;
            k --;
        }
        while(n2 != null) {
            n1 = n1.next;
            n2 = n2.next;
        }
        return n1;
    }
}
